package com.smarthome.web.property.controller.kuaidiXiyi;

import com.smarthome.base.service.ShAccountService;
import com.smarthome.base.service.ShOrdersService;
import com.smarthome.common.tools.excel.ReportExportService;
import com.smarthome.core.kuaidiXiyi.RecevieCourierService;
import com.smarthome.domain.bean.ShOrders;
import com.smarthome.domain.bean.ShResidence;
import com.smarthome.domain.common.Result;
import com.smarthome.domain.enums.OrdersPaymentStatus;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;
import com.smarthome.domain.vo.boss.TimeRange;
import com.smarthome.web.property.utils.UserHolder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/recevieCourier")
public class ReceiveCourierController {

    @Resource
    private RecevieCourierService recevieCourierService;

    @Resource
    private ShOrdersService shOrdersService;

    @Resource
    private ShAccountService shAccountService;

    /**
     * @param shOrders
     * @param page
     * @param timeRange
     * @return DataGrid
     * @throws
     * @Title: dataGrid
     * @Description: 获取代发快递datagrid
     */
    @RequestMapping("/dataGrid")
    @ResponseBody
    public DataGrid dataGrid(ShOrders shOrders, PageHelper page, TimeRange timeRange) {
        if (timeRange.getStartGmtCreate() != null) {
            shOrders.addQueryData("startGmtCreate", timeRange.getStartGmtCreate());
        }
        if (timeRange.getEndGmtCreate() != null) {
            shOrders.addQueryData("endGmtCreate", timeRange.getEndGmtCreate());
        }
        if (timeRange.getStartGmtModify() != null) {
            shOrders.addQueryData("startGmtModify", timeRange.getStartGmtModify());
        }
        if (timeRange.getEndGmtModify() != null) {
            shOrders.addQueryData("endGmtModify", timeRange.getEndGmtModify());
        }

        shOrders.setResidenceId(UserHolder.getCurrentResidenceId());
        shOrders.setOrderType(1);
        shOrders.addQueryData("notStatus", new Integer[]{4});
        return recevieCourierService.dataGrid(shOrders, page);
    }

    /**
     * 跳转到添加页面
     *
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(HttpServletRequest request) {
        return "/kuaidiXiyi/recevieCourierAdd";
    }


    /**
     * 新增
     *
     * @param request
     * @param shOrders
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result add(HttpServletRequest request, ShOrders shOrders) {
        if (shOrders.getCompanyId() == null) {
            return Result.failure("请选择快递点！");
        }
        if (StringUtils.isBlank(shOrders.getName())) {
            return Result.failure("请输入订单名称！");
        }
        if (StringUtils.isBlank(shOrders.getDesMobile())) {
            return Result.failure("请输入收件人手机号！");
        }

        try {
            shOrders.setResidenceId(UserHolder.getCurrentResidenceId());
            Integer result = recevieCourierService.add(shOrders);
            if (result == 1) {
                recevieCourierService.sendMsg(shOrders);
                return Result.success("添加成功！");
            } else {
                return Result.failure("添加待取快递失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("系统异常，添加待取快递失败！");
        }
    }

    /**
     * @param request
     * @param id
     * @return String
     * @throws
     * @Title: editPage
     * @Description: 跳转修改页面
     */
    @RequestMapping("/editPage")
    public String editPage(HttpServletRequest request, Long id) {
        ShOrders shOrders = recevieCourierService.getDetailById(id);
        request.setAttribute("shOrders", shOrders);
        return "/kuaidiXiyi/recevieCourierEdit";
    }


    /**
     * 修改
     *
     * @param shOrders
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Result edit(ShOrders shOrders) {
        if (shOrders.getCompanyId() == null) {
            return Result.failure("请选择快递点！");
        }
        if (StringUtils.isBlank(shOrders.getName())) {
            return Result.failure("请输入订单名称！");
        }
        if (StringUtils.isBlank(shOrders.getDesMobile())) {
            return Result.failure("请输入收件人手机号！");
        }

        if (shOrders.getStatus() == null) {
            return Result.failure("请选择状态！");
        }

        try {
            ShResidence nowResidence = UserHolder.getCurrentResidence();
            if (shOrders.getStatus().intValue() == 2) {
                shOrders.setPaymentStatus(OrdersPaymentStatus.CASH.getType());//未支付
            }
            shOrders.setSrcAreaId(nowResidence.getAreaId());
            shOrders.setHandler(UserHolder.getUser().getEmployeeName());
            Integer result = recevieCourierService.edit(shOrders);
            if (result == 1) {
                return Result.success("修改成功！");
            } else {
                return Result.failure("未找到指定订单，修改失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("系统异常，修改失败！");
        }
    }

    /**
     * @param id
     * @return Result
     * @throws
     * @Title: delete
     * @Description: 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(Long id) {
        try {
            Integer result = recevieCourierService.chengeStatus(id, 4);
            return 1 == recevieCourierService.chengeStatus(id, 4)
                    ? Result.success("删除成功！")
                    : Result.failure("未找到指定订单，删除失败！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success("系统异常，删除失败！");
        }
    }

    @RequestMapping(value = "/warehouseOut", method = RequestMethod.POST)
    @ResponseBody
    public Result warehouseOut(Long id, String expressNumber) {
        ShOrders existed = null;
        if (null != id && id > 0) {
            existed = shOrdersService.selectEntryById(id);
        } else if (StringUtils.isNotBlank(expressNumber)) {
            ShOrders condition = new ShOrders();
            condition.setOutBizNum(expressNumber.trim());
            condition.setStatus(1); // 待取快递
            condition.setResidenceId(UserHolder.getCurrentResidenceId());
            List<ShOrders> orders = recevieCourierService.getRecevieCourierDetailList(condition);

            if (CollectionUtils.isNotEmpty(orders)) {
                existed = orders.get(0);
            }
        }

        // 没有查到数据
        if (null == existed) {
            return Result.failure("未找到指定订单，签收失败！");
        }

        if (null != existed.getStatus() && 1 != existed.getStatus()) {
            return Result.failure("此定订单已经签收，签收失败！");
        }

        try {
            // 更新
            existed.setStatus(2);
            return 1 == shOrdersService.saveOrUpdate(existed)
                    ? Result.success("签收成功！")
                    : Result.failure("未找到指定订单，签收失败！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success("系统异常，签收失败！");
        }
    }


    @RequestMapping("/notice")
    @ResponseBody
    public Result orderNotice(Long id) {
        ShOrders order = recevieCourierService.getDetailById(id);
        boolean back = recevieCourierService.sendMsg(order);
        if (!back) {
            //return Result.failure("通知失败!");
        }
        return Result.success("通知成功!");
    }

    /**
     * @param response
     * @param shOrders
     * @param timeRange
     * @throws IOException void
     * @throws
     * @Title: downloadExcel
     * @Description: 导出excel
     * @author cyj
     */
    @RequestMapping(value = "/downloadExcel", method = {RequestMethod.GET})
    public void downloadExcel(HttpServletResponse response, ShOrders shOrders, TimeRange timeRange) throws IOException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH");
        String title = "快递待取统计导出" + dateFormat.format(new Date()) + ".xls";
        List<String> headerNames = new ArrayList<String>();
        headerNames.add("快递单号");
        headerNames.add("状态");
        headerNames.add("订单名称");
        headerNames.add("快递公司");
        headerNames.add("收件人");
        headerNames.add("收件人电话");
        headerNames.add("快递费用（元）");
        headerNames.add("创建时间");
        headerNames.add("修改时间");
        List<String> cellNames = new ArrayList<String>();
        cellNames.add("outBizNum");
        cellNames.add("status");
        cellNames.add("name");
        cellNames.add("companyName");
        cellNames.add("desAccountName");
        cellNames.add("desMobile");
        cellNames.add("amount");
        cellNames.add("gmtCreate");
        cellNames.add("gmtModify");

        if (timeRange.getStartGmtCreate() != null) {
            shOrders.addQueryData("startGmtCreate", timeRange.getStartGmtCreate());
        }
        if (timeRange.getEndGmtCreate() != null) {
            shOrders.addQueryData("endGmtCreate", timeRange.getEndGmtCreate());
        }
        if (timeRange.getStartGmtModify() != null) {
            shOrders.addQueryData("startGmtModify", timeRange.getStartGmtModify());
        }
        if (timeRange.getEndGmtModify() != null) {
            shOrders.addQueryData("endGmtModify", timeRange.getEndGmtModify());
        }

        shOrders.setResidenceId(UserHolder.getCurrentResidenceId());

        List<Object> datas = new ArrayList<Object>();
        shOrders.setOrderType(1);//待取快递
        List<ShOrders> shOrdersList = recevieCourierService.getRecevieCourierDetailList(shOrders);

        if (shOrdersList != null) {
            int length = shOrdersList.size();
            ShOrders order = null;
            Map<String, Object> data = null;
            dateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < length; i++) {
                order = shOrdersList.get(i);
                data = new HashMap<String, Object>();
                data.put("outBizNum", order.getOutBizNum());
                data.put("name", order.getName());
                data.put("companyName", order.getCompanyName());
                data.put("desAccountName", order.getDesAccountName());
                data.put("desMobile", order.getDesMobile());
                double amount = order.getAmount() == null ? 0d : (double) order.getAmount() / 100;
                data.put("amount", amount);
                int status = order.getStatus().intValue();
                if (status == 1) {
                    data.put("status", "待取");
                } else if (status == 2) {
                    data.put("status", "已取件");
                } else if (status == 3) {
                    data.put("status", "关闭");
                } else if (status == 4) {
                    data.put("status", "删除");
                } else {
                    data.put("status", "未知");
                }
                data.put("gmtCreate", dateFormat.format(order.getGmtCreate()));
                data.put("gmtModify", dateFormat.format(order.getGmtModify()));
                datas.add(data);
            }
        }

        new ReportExportService().doExportAndDownload(title, headerNames, cellNames, datas, response);
    }

}
